/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package others.DAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.faces.context.FacesContext;
import login.bean.LoginBean;

/**
 *
 * @author chucho
 */
public class ExecuteStatementDAO {

    public Connection conn;
    private LoginBean lb ;
    
    public ExecuteStatementDAO() {
                lb = (LoginBean) FacesContext.getCurrentInstance()
                .getExternalContext().getSessionMap().get("loginBean");
        this.conn = lb.getCurrentConnection();
    }

    public String doStatement(String sqlReceive) {
        try {
            StringBuilder response = new StringBuilder();
            Statement statement = conn.createStatement();
            String sql = sqlReceive;
            if (statement.execute(sql)) {
                do {
                    ResultSet resultSet = statement.getResultSet();
                    for (int i = 1; i < resultSet.getMetaData().getColumnCount(); i++) {
                        response.append(resultSet.getMetaData().getColumnName(i));
                        response.append("       ");
                    }
                    while (resultSet.next()) {
                        response.append(System.getProperty("line.separator"));
                        for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
                            response = response.append(resultSet.getString(i));
                            response.append("        ");
                        }
                    }
                } while (statement.getMoreResults() != false);
                return response.toString();
            } else {
                int re = statement.getUpdateCount();
                return "execute OK. " + re + " Filas Afectadas";
            }
        } catch (SQLException e) {
            return e.getMessage();
        }
    }

    public ResultSet doSQL(String sqlReceive) {
        try {
            Statement statement = conn.createStatement();
            String sql = sqlReceive;
            ResultSet resultSet = statement.executeQuery(sql);
            return resultSet;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
